package org.jeecg.modules.publish.controller;

import com.alibaba.fastjson.JSONObject;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.DateTimeUtil;
import org.jeecg.common.util.OnlinePicUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.activity.entity.ActivityInfo;
import org.jeecg.modules.activity.service.IActivityInfoService;
import org.jeecg.modules.content.entity.BasThirdInfo;
import org.jeecg.modules.content.entity.ContentGoto;
import org.jeecg.modules.content.entity.ContentInfo;
import org.jeecg.modules.content.service.IContentGotoService;
import org.jeecg.modules.publish.entity.ThirdContentLink;
import org.jeecg.modules.publish.service.IThirdContentLinkService;
import org.jeecg.modules.publish.util.WeixinInterface;
import org.jeecg.util.DouYinUtil;
import org.jeecg.util.WeiBoUtil;
import org.jeecgframework.p3.core.util.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description: 第三方平台发布
 * @Author: wufanxin
 * @Date:   2020-07-05
 * @Version: V1.0
 */
@Slf4j
@Api(tags="第三方平台发布")
@RestController
@RequestMapping("/publish/third")
public class PublishController extends JeecgController<ActivityInfo, IActivityInfoService> {

    @Autowired
    IThirdContentLinkService weixinContentLinkService;

    @Autowired
    IContentGotoService contentGotoService;
    /**
     * 微信发布
     *
     * @return
     */
    @AutoLog(value = "第三方平台发布-微信发布")
    @ApiOperation(value="第三方平台发布-微信发布", notes="第三方平台发布-微信发布")
    @PostMapping(value = "/weixinShare")
    public Result<?> weixinShare(@RequestBody Map<String,Object> reqMap,
                                 HttpServletRequest req) {
        Map<String,Object> thirdMap = (Map<String,Object>)reqMap.get("thirdInfo");
        BasThirdInfo thirdInfo = new BasThirdInfo();
        thirdInfo.setClientKey(thirdMap.get("clientKey").toString());
        thirdInfo.setClientSecret(thirdMap.get("clientSecret").toString());

        List<Map<String,Object>> contentMapList =  (List<Map<String,Object>>)reqMap.get("contentList");
        List<ContentInfo> contentInfoList = new ArrayList<>();
        contentMapList.stream().forEach(item->{
            ContentInfo contentInfo = new ContentInfo();
            contentInfo.setAuthorName(null != item.get("authorName")?item.get("authorName").toString():"");
            contentInfo.setContent(null!=item.get("content")?item.get("content").toString():"");
            contentInfo.setContentTitle(null!=item.get("contentTitle")?item.get("contentTitle").toString():"");
            contentInfo.setMbLogoUrl(null != item.get("mbLogoUrl")?item.get("mbLogoUrl").toString():"");
            contentInfo.setContentIntroduce(null != item.get("contentIntroduce")?item.get("contentIntroduce").toString():"");
            contentInfo.setHtmlUrl(null != item.get("htmlUrl")?item.get("htmlUrl").toString():"");
            contentInfoList.add(contentInfo);

            ContentGoto contentGoto = new ContentGoto();
            contentGoto.setId(UUIDGenerator.generate());
            contentGoto.setContent_id(item.get("contentNo").toString());
            contentGoto.setDest(4);
            contentGotoService.save(contentGoto);

        });

        Result rs = WeixinInterface.updoadToWeixin(contentInfoList,thirdInfo);
        System.out.println("微信返回结果："+rs.toString());
        String mediaId = rs.getMessage();
        //拼装绑定参数
        List<ThirdContentLink> linkList  = new ArrayList<>();
        for(Map<String,Object> contentInfo:contentMapList){
            ThirdContentLink link = new ThirdContentLink();
            link.setId(mediaId);
            link.setType(1);
            link.setContentId(contentInfo.get("id").toString());
            link.setWeixinKey(thirdMap.get("clientKey").toString());
            link.setWeixinSecret(thirdMap.get("clientSecret").toString());
            link.setDate(new Date());

            linkList.add(link);
        }
        weixinContentLinkService.saveBatch(linkList);

        return Result.ok("发布成功");
    }




    /**
     * 微信发布
     *
     * @return
     */

    @PostMapping(value = "/weiBoShare")
    public Result<?> weiBoShare(@RequestBody Map<String,Object> reqMap,
                                HttpServletRequest req) {
        Map<String,Object> thirdMap = (Map<String,Object>)reqMap.get("thirdInfo");
        BasThirdInfo thirdInfo = new BasThirdInfo();
        thirdInfo.setClientKey(thirdMap.get("clientKey").toString());
        thirdInfo.setClientSecret(thirdMap.get("clientSecret").toString());

        String token = WeiBoUtil.getAccessToken( thirdMap.get("clientKey").toString(),thirdMap.get("clientSecret").toString(),thirdMap.get("code").toString());

        List<Map<String,Object>> contentMapList =  (List<Map<String,Object>>)reqMap.get("contentList");
        Map<String,Boolean> resultMap = new HashMap<>();

        contentMapList.stream().forEach(item->{
            Map<String,String > paramMap = new HashMap<>();
            paramMap.put("title",null != item.get("title")?item.get("title").toString():"");
            try {

                paramMap.put("cover",URLEncoder.encode(item.get("title").toString(),"utf-8"));
               // paramMap.put("cover",item.get("cover").toString());
                paramMap.put("text",item.get("text").toString());
                paramMap.put("access_token",token);
                String post = HttpUtils.doPostJson("https://api.weibo.com/proxy/article/publish.json", JSONObject.toJSONString(paramMap));
                JSONObject jsonObject = JSONObject.parseObject(post);
                if( jsonObject.getString("code").equals("100000")){

                    String mid = jsonObject.getJSONObject("data").getString("|__ mid");
                    ThirdContentLink thirdContentLink = new ThirdContentLink();
                    thirdContentLink.setId(mid);
                    thirdContentLink.setType(4);
                    thirdContentLink.setContentId(item.get("id").toString());
                    thirdContentLink.setDate(new Date());
                    thirdContentLink.setAccountId(thirdMap.get("accountId").toString()) ;
                weixinContentLinkService.save(thirdContentLink);

                    resultMap.put(item.get("title").toString(),true);

                }else {
                    resultMap.put(item.get("title").toString(),false);

                }

            } catch (Exception e) {
                resultMap.put(item.get("title").toString(),false);

                e.printStackTrace();
            }



        });

        return Result.ok(resultMap);
    }




    /**
     * 微信发布
     *
     * @return
     */
    @PostMapping(value = "/douYinShare")
    public Result<?> douyinShare(@RequestBody Map<String,Object> reqMap,
                                 HttpServletRequest req) throws IOException {
        Map<String,Object> thirdMap = (Map<String,Object>)reqMap.get("thirdInfo");

        String url = reqMap.get("url").toString();
        List<Map<String,Object>> contentMapList =  (List<Map<String,Object>>)reqMap.get("contentList");

        //获取抖音openId 和accessToken
        Map<String,String>  paramMap = DouYinUtil.getDouYinInfo(thirdMap.get("clientKey").toString(),thirdMap.get("clientSecret").toString(),thirdMap.get("code").toString());
        Map<String,Boolean> resultMap = new HashMap<>();

        contentMapList.stream().forEach(item->{

            try {
                Map<String,Object> map = douYinUpload (url, item.get("filePath").toString(), item.get("fileName").toString(),paramMap.get("openId") ,paramMap.get("token") );
                resultMap.put(item.get("fileName").toString(),(boolean)map.get("flag"));
                if((boolean)map.get("flag")){
                    ThirdContentLink thirdContentLink = new ThirdContentLink();
                    thirdContentLink.setId(map.get("videoId").toString());
                    thirdContentLink.setType(2);
                    thirdContentLink.setContentId(item.get("id").toString());
                    thirdContentLink.setDate(new Date());
                    weixinContentLinkService.save(thirdContentLink);
                }
            } catch (IOException e) {
                resultMap.put(item.get("fileName").toString(),false);

                e.printStackTrace();
            }
        });

        return Result.ok(resultMap);
    }






    public   Map<String,Object>  douYinUpload (String url,String fileUrl,String fileName,String openId,String token) throws IOException {
        String base64ByUrl = OnlinePicUtil.getBase64ByUrl(fileUrl);
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes =  decoder.decodeBuffer(base64ByUrl);

        HttpPost post = new HttpPost("https://open.douyin.com"+url+"?open_id="+openId+"?access_token="+token);
        HttpClient httpclient = HttpClientBuilder.create().build();

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("video", bytes, ContentType.MULTIPART_FORM_DATA, fileName);

        HttpEntity reqEntity = builder.build();
        post.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        Map<String,Object> map = new HashMap<>();
        map.put("flag",false);
        if (statusCode == HttpStatus.SC_OK) {
            log.info("上传成功");
            map.put("flag",true);
            HttpEntity httpEntity = response.getEntity();
            String entity = EntityUtils.toString(httpEntity);

            JSONObject jsonObject = JSONObject.parseObject(entity);
            JSONObject data = jsonObject.getJSONObject("data");
            String videoId = jsonObject.getJSONObject("video").getString("video_id");
            map.put("videoId",videoId);
            log.info(data.toJSONString());

        }

        return  map;
    }


    public   Map<String,String>  getDouYinInfo () throws IOException {

        String url = "https://open.douyin.com/oauth/access_token";
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        nameValuePairList.add(new BasicNameValuePair("client_secret", "client_secret"));
        nameValuePairList.add(new BasicNameValuePair("code", "code"));
        nameValuePairList.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nameValuePairList.add(new BasicNameValuePair("client_key", "client_key"));
        String result = HttpUtils.postForm(url, nameValuePairList);
        JSONObject jsonObject = JSONObject.parseObject(result);

        JSONObject data = jsonObject.getJSONObject("data");
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("access_token",data.get("access_token").toString());
        resultMap.put("open_id",data.get("open_id").toString());
        return  resultMap;

    }



}
